<?php
if (Request::post()) {
  require_once "../../vendor/autoload.php";
  require_once DOXCX_FRAME_PATH . '/fun/EloquentModels/EloquentModels.php';
  Page::$need_view = false;
  if (!arr_get($_POST, 'money') || arr_get($_POST, 'money') < 0.01) {
    sendResponse([
      'status' => 'error',
      'msg' => '请输入正确的金额'
    ]);
    exit();
  }
  //$admin = UserAgency::where('un', 'admin')->first();
  $uid = Session::get('mainuid');
  //$user = User::where('id', $uid)->first();
  $user = (new Model('user'))->find($uid);
  if($user->agid){
	 //$admin = UserAgency::where('id', $user->agid)->first();
	 $admin = (new Model('user_agency'))->find($user->agid);
  }else{
	 //$admin = UserAgency::where('isadmin', 1)->first();	
	 $admin = (new Model('user_agency'))->find(['isadmin'=>1]);
  }		
 
  $time = time();
  $nonce = md5($time . $uid . rand(0, 99999)); 
  //$out_trade_no = $uid . date('YmdHis', $time) . $time . rand(10000, 99999);
  $out_trade_no = date('YmdHis', $time) . $time . rand(10000, 99999);
  $domain=$_SERVER['HTTP_HOST'];
  $params = [
    'appid' => $admin->recharge_appid,
    'mch_id' => $admin->recharge_mchid,
    'nonce_str' => $nonce,
    'body' => '充值',
    'out_trade_no' => $out_trade_no,
    'total_fee' => intval($_POST['money'] * 100),
    'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
    'notify_url' => "https://". $domain. "/Payment/Wxpay/rechargeNotify.html",
    'trade_type' => 'NATIVE',
    'product_id' => '1',//商品ID
    'attach' => json_encode(['uid'=>$uid,'agid'=>$user->agid])
  ];
  $sign = make_sign($params, $admin->recharge_key);
  $params['sign'] = $sign;
  $client = new \GuzzleHttp\Client();
  $resp = $client->post("https://api.mch.weixin.qq.com/pay/unifiedorder", [
    'verify' => false,
    'body' => array_to_cdata_xml($params)
  ]);
  $body = $resp->getBody();
  $resp_arr = xml_to_array((string)$body);
  if (!arr_get($resp_arr, 'code_url')) {
    sendResponse([
      'status' => 'error',
      'msg' => $resp_arr['return_msg']
    ],true);
  }
  // 二维码接口
  sendResponse([
    'status' => 'success',
    'data' => "https://". $domain. "/payQrcode.html?url=".urlencode($resp_arr['code_url'])
  ]);
  exit();
}


